package com.dmgis.qxfw.dataservice.businessservice.yyly.service.Impl;



import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.satellitenephoram3;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.smallscale_station;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.sum_sun_day_data;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.township_forecasttemp;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.admin_table;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.dz_warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.fire_history;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.forest_diseases_index;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.hxyj_warning;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CloudSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.FirePointSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.FireSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.InsectSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.yyly.service.IForestryfcstService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("ForestryService")
public class ForestryfcstServiceImpl implements IForestryfcstService {

	HttpRequestUtil httpUtil = new HttpRequestUtil();
	ProcessRequestController pc = new ProcessRequestController();

	@Resource
	private ITransformService iTransformService;

	@Override
	public satellitenephoram3 getCloudNewDate() {
		// TODO 获取云图最新时间
		satellitenephoram3 newestDate = new satellitenephoram3();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String[] columns = new String[] { "dateChar", "timechar" };
		selectRequest.setColumns(columns);
		selectRequest.setSort(new String[] { "datechar desc", "timechar desc" });
		selectRequest.setLimit(1);
		try {
			selectParam.put("method", "satellitenephoram3");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			newestDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<satellitenephoram3>>() {
			}).get(0);
		} catch (Exception e) {
			newestDate.setDatechar(DateTime.now().toDate());
		}
		if (newestDate != null) {
			newestDate.setDatechar(newestDate.getDatechar());
		}
		return newestDate;
	}

	@Override
	public List<SatelliteYT> getCloudTypes() {
		return null;
		// TODO 获取云图参数
		// DbContextHolder.setDbType("qx");
		// return forecastInfoMapper.getCloudTypes();
		/*
		 * List<satellitenephoram3> listData = new
		 * ArrayList<satellitenephoram3>(); List<SatelliteNephoramKey>
		 * resultList = new ArrayList<SatelliteNephoramKey>(); Map<String,
		 * String> selectParam = new HashMap<String, String>();
		 * RequestDataBySelect selectRequest = new RequestDataBySelect();
		 * String[] columns = new String[] { "distinct yttype" };
		 * selectRequest.setColumns(columns); try { selectParam.put("method",
		 * "satellitenephoram"); selectParam.put("sqlType", "select");
		 * selectParam.put("param", JsonUtil.object2Json(selectRequest)); String
		 * message = httpUtil.sendPost(DbConfig.dmgismeteorourl, selectParam); listData =
		 * JsonUtil.jsonStr2TypeReference(message, new
		 * TypeReference<List<satellitenephoram3>>() { }); } catch (Exception e)
		 * { // TODO: handle exception } if (listData != null && listData.size()
		 * > 0) { for (satellitenephoram satel : listData) {
		 * SatelliteNephoramKey satellite = new SatelliteNephoramKey();
		 * satellite.setType(satel.getYttype()); resultList.add(satellite); } }
		 * return resultList;
		 */
	}

	@Override
	public List<SatelliteYT> getCloud(CloudSearch cloudSearch) {
		// TODO 获取云图
		List<satellitenephoram3> listData = new ArrayList<satellitenephoram3>();
		List<SatelliteYT> resultList = new ArrayList<SatelliteYT>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		List<String> columns = new ArrayList<String>();
		columns.add("datayear");
		columns.add("datechar");
		columns.add("TimeChar");
		columns.add("ytType");
		columns.add("Path");
		columns.add("SateTitle");
		columns.add("west");
		columns.add("south");
		columns.add("east");
		columns.add("north");
		columns.add("coordinates");
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		selectRequest.setSort(new String[] { "datechar desc", "timechar desc" });
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (cloudSearch.getDataYear() != null) {
			strWhere.append(String.format("dataYear='%d'", cloudSearch.getDataYear()));
			whereCount++;
		}
		if (cloudSearch.getDateChar() != null) {
			strWhere.append(String.format(" and dateChar='%tF'", cloudSearch.getDateChar()));
		}
		if (cloudSearch.getStartDate() != null) {
			strWhere.append(String.format(" and datechar>='%s'", cloudSearch.getStartDate()));
		}
		if (cloudSearch.getEndDate() != null) {
			strWhere.append(String.format(" and datechar<='%s'", cloudSearch.getEndDate()));
		}
		if (!StringUtil.IsNullOrEmpty(cloudSearch.getTimeChar())) {
			strWhere.append(String.format(" and timeChar='%s'", cloudSearch.getTimeChar()));
		}
		if (!StringUtil.IsNullOrEmpty(cloudSearch.getType())) {
			strWhere.append(String.format(" and yttype='%s'", cloudSearch.getType()));
		}
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "satellitenephoram4");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<satellitenephoram3>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (listData != null && listData.size() > 0) {
			for (satellitenephoram3 sate : listData) {
				SatelliteYT satellite = new SatelliteYT();
				satellite.setDataYear(sate.getDatayear());
				satellite.setDateChar(new DateTime(sate.getDatechar()).toDateString());
				satellite.setTimeChar(sate.getTimechar());
				satellite.setType(sate.getYttype());
				satellite.setPath(sate.getPath());
				satellite.setFxmin(sate.getWest());
				satellite.setFxmax(sate.getEast());
				satellite.setFymin(sate.getSouth());
				satellite.setFymax(sate.getNorth());
				satellite.setCoordinates(sate.getCoordinates());
				resultList.add(satellite);
			}
		}
		return resultList;
	}

	@Override
	public HXYJ_Warning getFireNewDate() {
		// TODO 获取火险预警最新时间
		HXYJ_Warning result = new HXYJ_Warning();
		hxyj_warning newestDate = new hxyj_warning();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String[] columns = new String[] { "dateChar" };
		selectRequest.setColumns(columns);
		selectRequest.setSort(new String[] { "datechar desc" });
		selectRequest.setParam("warningtype = '1'");
		selectRequest.setLimit(1);
		try {
			selectParam.put("method", "hxyj_warning");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			newestDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<hxyj_warning>>() {
			}).get(0);
		} catch (Exception e) {
			newestDate.setDatechar(DateTime.now().toDate());
		}
		if (newestDate != null) {
			result.setDateChar(newestDate.getDatechar());
		}
		return result;
	}

	@Override
	public List<HXYJ_Warning> getFirewarning(FireSearch firesearch) {
		// TODO 获取火险预警
		List<hxyj_warning> listData = new ArrayList<hxyj_warning>();
		List<HXYJ_Warning> resultList = new ArrayList<HXYJ_Warning>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		List<String> columns = new ArrayList<String>();
		columns.add("docid");
		columns.add("datechar");
		columns.add("State");
		columns.add("GradeArea3");
		columns.add("GradeArea4");
		columns.add("GradeArea5");
		columns.add("Pos");
		columns.add("Docpath");
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		selectRequest.setSort(new String[] { "datechar desc" });
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (!StringUtil.IsNullOrEmpty(firesearch.getDocid())) {
			strWhere.append(String.format(" and docid='%s'", firesearch.getDocid()));
		}
		if (!StringUtil.IsNullOrEmpty(firesearch.getStartDate())) {
			strWhere.append(String.format(" and datechar>='%s'", firesearch.getStartDate()));
		}
		if (!StringUtil.IsNullOrEmpty(firesearch.getEndDate())) {
			strWhere.append(String.format(" and datechar<='%s'", firesearch.getEndDate()));
		}
		if(!StringUtil.IsNullOrEmpty(firesearch.getType())){
			strWhere.append(String.format(" and warningtype='%s'", firesearch.getType()));
		}
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "hxyj_warning");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<hxyj_warning>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (listData != null && listData.size() > 0) {
			for (hxyj_warning hxyj_warn : listData) {
				HXYJ_Warning HXYJ_warning = new HXYJ_Warning();
				HXYJ_warning.setDocid(hxyj_warn.getDocid());
				HXYJ_warning.setDateChar(hxyj_warn.getDatechar());
				HXYJ_warning.setGradeArea3(hxyj_warn.getGradearea3());
				HXYJ_warning.setGradeArea4(hxyj_warn.getGradearea4());
				HXYJ_warning.setGradeArea5(hxyj_warn.getGradearea5());
				HXYJ_warning.setState(hxyj_warn.getState());
				HXYJ_warning.setShFlag(hxyj_warn.getShflag());
				HXYJ_warning.setPos(hxyj_warn.getPos());
				HXYJ_warning.setDocpath(hxyj_warn.getDocpath());
				resultList.add(HXYJ_warning);
			}
		}
		return resultList;
	}


	@Override
	public List<Insectpests> getInsectpests(InsectSearch selectKey) {
		// TODO 获取病虫害
		List<forest_diseases_index> listData = new ArrayList<forest_diseases_index>();
		List<Insectpests> resultList = new ArrayList<Insectpests>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		List<String> columns = new ArrayList<String>();
		columns.add("plantname");
		columns.add("diseasesname");
		columns.add("starttime");
		columns.add("endtime");
		columns.add("mintemp");
		columns.add("maxtemp");
		columns.add("minrain");
		columns.add("maxrain");
		columns.add("minwindv");
		columns.add("maxwindv");
		columns.add("sunhour");
		columns.add("defendmessures");
		columns.add("county");
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (!StringUtil.IsNullOrEmpty(selectKey.getZbnames())) {
			strWhere.append(String.format("and plantname='%s'", selectKey.getZbnames()));
		}
		if (!StringUtil.IsNullOrEmpty(selectKey.getDisaster())) {
			strWhere.append(String.format("and diseasesname='%s'", selectKey.getDisaster()));
		}
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "forest_diseases_index");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			System.out.println(message);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forest_diseases_index>>() {
			});
		} catch (Exception e) {
			System.out.println("error!");
		}
		if (listData != null && listData.size() > 0) {
			for (forest_diseases_index fdindex : listData) {
				Insectpests insectpests = new Insectpests();
				insectpests.setPlantname(fdindex.getPlantname());
				insectpests.setDiseasesname(fdindex.getDiseasesname());
				insectpests.setStarttime(fdindex.getStarttime());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = fdindex.getEndtime();
				insectpests.setEndtime(sdf.format(date));
				insectpests.setMintemp(fdindex.getMintemp());
				insectpests.setMaxtemp(fdindex.getMaxtemp());
				insectpests.setMinrain(fdindex.getMinrain());
				insectpests.setMaxrain(fdindex.getMaxrain());
				insectpests.setMinwindv(fdindex.getMinwindv());
				insectpests.setMaxwindv(fdindex.getMaxwindv());
				insectpests.setSunhour(fdindex.getSunhour());
				insectpests.setCounty(fdindex.getCounty());
				insectpests.setDefendmessures(fdindex.getDefendmessures());
				resultList.add(insectpests);
			}
		}
		return resultList;
	}

	@Override
	public base_product getSpeServiceNewDate() {
		// TODO 初始化专题服务界面
		base_product result = new base_product();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String[] columns = new String[] { "forecasttime" };
		selectRequest.setColumns(columns);
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		strWhere.append(" and producttype='专题服务'");
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		selectRequest.setSort(new String[] { "forecasttime desc" });
		selectRequest.setLimit(1);
		try {
			selectParam.put("method", "base_product");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			if(!message.equals("[]")){
				result = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
				}).get(0);
			}
		} catch (Exception e) {
			System.out.println("error!");
		}
		return result;
	}

	@Override
	public List<base_product> getServiceDoc(String date) {
		// TODO 得到专题服务文档
		List<base_product> result = new ArrayList<base_product>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		List<String> columns = new ArrayList<String>();
		columns.add("id");
		columns.add("productname");
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (date != null) {
			strWhere.append(String.format("and 	DATE(forecasttime)='%s'", date));
		}
		strWhere.append(" and producttype='专题服务'");
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "base_product");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			System.out.println(message);
			result = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
			});
		} catch (Exception e) {
			System.out.println("error!");
		}
		return result;
	}

	@Override
	public List<DZWarning> getDZAreaDoc(String docid) {
		// TODO 获取地灾预警信息
		List<dz_warning> listData = new ArrayList<dz_warning>();
		List<DZWarning> resultList = new ArrayList<DZWarning>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (!StringUtil.IsNullOrEmpty(docid)) {
			strWhere.append(String.format(" and docid='%s'", docid));
		}
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setLimit(1);
		selectRequest.setParam(strWhere.toString());
		selectRequest.setSort(new String[]{"datechar desc"});
		try {
			selectParam.put("method", "hxyj_warning");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<dz_warning>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (listData != null && listData.size() > 0) {
			for (dz_warning dzWarn : listData) {
				DZWarning dzWarning = new DZWarning();
				dzWarning.setDocid(dzWarn.getDocid());
				dzWarning.setDateChar(dzWarn.getDatechar());
				dzWarning.setPos(dzWarn.getPos());
				dzWarning.setGradeArea2(dzWarn.getGradearea2());
				dzWarning.setGradeArea3(dzWarn.getGradearea3());
				dzWarning.setGradeArea4(dzWarn.getGradearea4());
				dzWarning.setGradeArea5(dzWarn.getGradearea5());
				dzWarning.setDocpath(dzWarn.getDocpath());
				resultList.add(dzWarning);
			}
		}
		return resultList;
	}

	@Override
	public List<FirePoint> getFirePoint(FirePointSearch selectKey) throws Exception {
		// TODO 得到历史火点
		List<fire_history> listData = new ArrayList<fire_history>();
		List<FirePoint> result = new ArrayList<FirePoint>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String[] columns = new String[] { "id", "firename", "address", "stationname", "announcedtime", "disasterarea",
				"popthreat", "propertythreat", "longitude", "latitude" };
		selectRequest.setColumns(columns);
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		// 依次判断灾害名称、发生地、最近监测点、灾害面积、至、威胁人口（人）、至、威胁财产（万元）、至是否非空，
		// 再进行条件的查询
		if (!StringUtil.IsNullOrEmpty(selectKey.getFirename())) {
			strWhere.append(String.format("and firename like '%%%s%%'", selectKey.getFirename()));
		}
		if (!StringUtil.IsNullOrEmpty(selectKey.getAddress())) {
			strWhere.append(String.format(" and address like '%%%s%%'", selectKey.getAddress()));
		}
		if (!StringUtil.IsNullOrEmpty(selectKey.getStationname())) {
			strWhere.append(String.format(" and stationname like '%%%s%%'", selectKey.getStationname()));
		}
		if (selectKey.getDisasterareato() != null && Integer.parseInt(selectKey.getDisasterareato()) > 0) {
			strWhere.append(String.format(" and disasterarea >='%s'", selectKey.getDisasterarea()));
			strWhere.append(String.format(" and disasterarea <= '%s'" , selectKey.getDisasterareato()));
		}
		if (selectKey.getPopthreatto() != null && Integer.parseInt(selectKey.getPopthreatto()) > 0) {
			strWhere.append(String.format(" and popthreat >='%s'", selectKey.getPopthreat()));
			strWhere.append(String.format(" and popthreat <= '%s'" , selectKey.getPopthreatto()));
		}
		if (selectKey.getPropertythreatto() != null && Integer.parseInt(selectKey.getPropertythreatto()) > 0) {
			strWhere.append(String.format(" and propertythreat >='%s'", selectKey.getPropertythreat()));
			strWhere.append(String.format(" and propertythreat <= '%s'" , selectKey.getPropertythreatto()));
		}
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "fire_history");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			System.out.println(message);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<fire_history>>() {
			});
		} catch (Exception e) {
			System.out.println("error!");
		}
		if (listData != null && listData.size() > 0) {
			for (fire_history fire : listData) {
				FirePoint firepoint = new FirePoint();
				firepoint.setId(fire.getId());
				firepoint.setFirename(fire.getFirename());
				firepoint.setAddress(fire.getAddress());
				firepoint.setStationName(fire.getStationname());
				firepoint.setAnnouncedtime(new DateTime(fire.getAnnouncedtime()).toDateTimeString());
				firepoint.setDisasterarea(fire.getDisasterarea());
				firepoint.setPopthreat(fire.getPopthreat());
				firepoint.setPropertythreat(fire.getPropertythreat());
				firepoint.setLon(fire.getLongitude());
				firepoint.setLat(fire.getLatitude());
				DmMapPoint dmDot = new DmMapPoint(fire.getLongitude(), fire.getLatitude());
				DmMapPoint ltDot = iTransformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
				firepoint.setX(ltDot.x);
				firepoint.setY(ltDot.y);
				result.add(firepoint);
			}
		}
		return result;
	}

	@Override
	public List<Insectpests> initInsectpests() {
		// TODO 病虫害
		List<forest_diseases_index> listData = new ArrayList<forest_diseases_index>();
		List<Insectpests> resultList = new ArrayList<Insectpests>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		List<String> columns = new ArrayList<String>();
		columns.add("distinct plantname");
		columns.add("diseasesname");
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		try {
			selectParam.put("method", "forest_diseases_index");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			System.out.println(message);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forest_diseases_index>>() {
			});
		} catch (Exception e) {
			System.out.println("error!");
		}
		if (listData != null && listData.size() > 0) {
			for (forest_diseases_index fdindex : listData) {
				Insectpests insectpests = new Insectpests();
				insectpests.setPlantname(fdindex.getPlantname());
				insectpests.setDiseasesname(fdindex.getDiseasesname());
				resultList.add(insectpests);
			}
		}
		return resultList;
	}

	@Override
	public String getProductID(String docpath) {
		// TODO Auto-generated method stub
		List<base_product> listData = new ArrayList<base_product>();
		String result = "";
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		StringBuilder strWhere = new StringBuilder();
		if (!StringUtil.IsNullOrEmpty(docpath)) {
			strWhere.append(String.format("productname='%s' ", docpath));
			// 改为参数化形式
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "base_product");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (listData != null && listData.size() > 0) {
			for (base_product dzWarn : listData) {
				result = dzWarn.getBindid().toString();
			}
		}
		return result;
	}

	@Override
	public Insectpests getYBInsectpests(String[] strCountys, Insectpests pests, DateTime date,
			boolean NoWonditions) {
		// TODO 得到病虫害预报信息
		Insectpests pst = new Insectpests();
		List<township_forecasttemp> list1 = new ArrayList<township_forecasttemp>();
		List<smallscale_station> list2 = new ArrayList<smallscale_station>();
		List<admin_table> adminTables = new ArrayList<>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		StringBuilder strWhere = new StringBuilder();
		try {
			for (int i = 0; i < strCountys.length; i++) {
				String strStaName = strCountys[i].trim();
				String[] columns = new String[] { "county", "countyid" };
				selectRequest.setColumns(columns);
				strWhere.append(String.format("city like '%s'", DbConfig.CITY + "市"));
				strWhere.append(String.format(" and county = '%s'", strStaName));
				selectRequest.setParam(strWhere.toString());
				selectParam.clear();
				selectParam.put("method", "admin_table");
				selectParam.put("sqlType", "select");
				selectParam.put("advCode", DbConfig.advCode);
				selectParam.put("&param", JsonUtil.object2Json(selectRequest));
				String message = pc.processRequest(selectParam);
				adminTables= JsonUtil
						.jsonStr2TypeReference(message, new TypeReference<List<admin_table>>() {
						});
				String strForecastStaID = "";
				if (adminTables != null && adminTables.size() > 0) {
					 strForecastStaID = adminTables.get(0).getCountyid();
				}
				int flag = 0;
				int conditionNum = 0;// ，满足的条件数
				int iflag = 1;
				boolean noSatCondition = false;// 不满足条件
				// 温度
				if (pests.getMaxtemp() != null && pests.getMintemp() != null) {
					selectRequest = new RequestDataBySelect();
					strWhere = new StringBuilder();
					columns = new String[] {
							"(case when maxtemp=-65535 then 0 else maxtemp end %2b case when mintemp=-65535 then 0 else mintemp end) / 2 as maxtemp" };
					selectRequest.setColumns(columns);
					if (StringUtil.IsNullOrEmpty(GetFilter(
							"(case when maxtemp=-65535 then 0 else maxtemp end %2b case when mintemp=-65535 then 0 else mintemp end) / 2 as maxtemp",
							pests.getMaxtemp().toString(), pests.getMintemp().toString()))) {
						flag = 0;
					} else {
						if (date != null) {
							strWhere.append(String.format(" and datechar = '%s' AND NTimes = '24' AND TimeChar = '20'",
									date.AddDays(-1)));
						}
						if (!StringUtil.IsNullOrEmpty(strForecastStaID)) {
							strWhere.append(String.format(" and stationID = '%s' and ", strForecastStaID));
						}
						strWhere.append(GetFilter(
								"(case when maxtemp=-65535 then 0 else maxtemp end %2b case when mintemp=-65535 then 0 else mintemp end) / 2 as maxtemp",
								pests.getMaxtemp().toString(), pests.getMintemp().toString()));
						if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
							strWhere = strWhere.replace(0, 4, "");
						}
						selectRequest.setParam(strWhere.toString());
						selectParam.clear();
						selectParam.put("method", "township_forecasttemp");
						selectParam.put("sqlType", "select");
						selectParam.put("&param", JsonUtil.object2Json(selectRequest));
						message = pc.processRequest(selectParam);
						list1 = JsonUtil.jsonStr2TypeReference(message,
								new TypeReference<List<township_forecasttemp>>() {
								});

						flag = list1.size();
						iflag = flag;
					}
					if (flag > 0) {
						conditionNum++;
					} else if (iflag == 0) {
						noSatCondition = true;
					}
					flag = 0;
					iflag = 1;
				}
				// 降水
				if (pests.getMaxrain() != null && pests.getMinrain() != null) {
					selectRequest = new RequestDataBySelect();
					strWhere = new StringBuilder();
					columns = new String[] { "avg(case when rain=-65535 then 0 else rain end)" };
					selectRequest.setColumns(columns);
					if (StringUtil.IsNullOrEmpty(GetFilter("avg(case when rain=-65535 then 0 else rain end)",
							pests.getMaxrain().toString(), pests.getMinrain().toString()))) {
						flag = 0;
					} else {
						if (date != null) {
							strWhere.append(String.format(" and datechar = '%s' AND NTimes = '24' AND TimeChar = '20'",
									date.AddDays(-1)));
						}
						strWhere.append(String.format(" and stationID = '%s' and ", strForecastStaID));
						strWhere.append(GetFilter(
								"(case when maxtemp=-65535 then 0 else maxtemp end %2b case when mintemp=-65535 then 0 else mintemp end) / 2 as maxtemp",
								pests.getMaxrain().toString(), pests.getMinrain().toString()));
						if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
							strWhere = strWhere.replace(0, 4, "");
						}
						selectRequest.setParam(strWhere.toString());
						selectParam.clear();
						selectParam.put("method", "township_forecasttemp");
						selectParam.put("sqlType", "select");
						selectParam.put("&param", JsonUtil.object2Json(selectRequest));
						message = pc.processRequest(selectParam);
						list1 = JsonUtil.jsonStr2TypeReference(message,
								new TypeReference<List<township_forecasttemp>>() {
								});
						flag = list1.size();
						iflag = flag;
					}
					if (flag > 0) {
						conditionNum++;
					} else if (iflag == 0) {
						noSatCondition = true;
					}
					flag = 0;
					iflag = 1;
				}

				// 日照数
				if (pests.getSunhour() != null) {
					if (Double.parseDouble(
							pests.getSunhour().toString() == "" ? "0" : pests.getSunhour().toString()) > 0) {
						selectRequest = new RequestDataBySelect();
						strWhere = new StringBuilder();
						columns = new String[] { "county" };
						selectRequest.setColumns(columns);
						strWhere.append(String.format("stationID = '%s' and ", strForecastStaID));
						selectRequest.setParam(strWhere.toString());
						selectParam.clear();
						selectParam.put("method", "smallscale_station");
						selectParam.put("sqlType", "select");
						selectParam.put("&param", JsonUtil.object2Json(selectRequest));
						message = pc.processRequest(selectParam);
						list2 = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
						});
						String county = list2.get(0).getCounty();

						selectRequest = new RequestDataBySelect();
						strWhere = new StringBuilder();
						columns = new String[] { "StationID" };
						selectRequest.setColumns(columns);
						strWhere.append(String.format("Stationname = '%s' and ", county));
						selectRequest.setParam(strWhere.toString());
						selectParam.clear();
						selectParam.put("method", "smallscale_station");
						selectParam.put("sqlType", "select");
						selectParam.put("&param", JsonUtil.object2Json(selectRequest));
						message = pc.processRequest(selectParam);
						list2 = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
						});
						if (list2.size() > 0) {
							strForecastStaID = list2.get(0).getStationid().toString();
						}

						DateTime time = date.AddDays(-1);
						selectRequest = new RequestDataBySelect();
						strWhere = new StringBuilder();
						columns = new String[] { "sumvalue" };
						selectRequest.setColumns(columns);
						strWhere.append(String.format("year = '%s' AND month = '%s' AND day = '%s' AND stationid ='%s'",
								time.GetYear(), time.GetMonth(), time.GetDay(), strForecastStaID));
						selectRequest.setParam(strWhere.toString());
						selectParam.clear();
						selectParam.put("method", "sum_sun_day_data");
						selectParam.put("sqlType", "select");
						selectParam.put("&param", JsonUtil.object2Json(selectRequest));
						message = pc.processRequest(selectParam);
						List<sum_sun_day_data> list3 = JsonUtil.jsonStr2TypeReference(message,
								new TypeReference<List<sum_sun_day_data>>() {
								});
						double sun;
						if (StringUtil.IsNullOrEmpty(list3.get(0).getSumvalue().toString())) {
							sun = 0;
						} else {
							sun = Double.parseDouble(list3.get(0).getSumvalue().toString());
						}
						if (sun > Double.parseDouble(pests.getSunhour().toString())) {
							conditionNum++;
						}
					} else {
						conditionNum++;
					}
				}
				if (NoWonditions || (conditionNum > 0 && !noSatCondition)) {
					pst.setPlantname(pests.getPlantname());
					pst.setDiseasesname(pests.getDiseasesname());
					pst.setCounty(strStaName);
					pst.setDefendmessures(pests.getDefendmessures());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pst;
	}

	@Override
	public List<hxyj_warning> getHXWarning() {
		List<hxyj_warning> listData = new ArrayList<hxyj_warning>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		selectRequest.setSort(new String[]{"datechar desc"});
		selectRequest.setLimit(1);
		try {
			selectParam.put("method", "hxyj_warning");
			selectParam.put("sqlType", "select");
			selectParam.put("advCode", DbConfig.advCode);
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<hxyj_warning>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listData;
	}

	private String GetFilter(String element, String strMax, String strMin) {
		String strWhere = "";
		if (element == "" || ((strMax == "") && (strMin == "")))
			return null;
		if (strMax == "") {
			strWhere = String.format("{0}>'{1}'", element, strMin);
		} else if (strMin == "") {
			strWhere = String.format("{0}<'{1}'", element, strMax);
		} else {
			strWhere = String.format(" {0} BETWEEN '{1}' and '{2}' ", element, strMin, strMax);
		}
		return strWhere;
	}
}
